<template>
  <div class="order-list-container">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <router-link to="/profile" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </router-link>
      <div class="navbar-title">我的订单</div>
      <div>
        <i class="fas fa-search"></i>
      </div>
    </div>

    <!-- 订单状态标签栏 -->
    <div class="tab-bar">
      <div 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="['tab-item', { active: currentTab === tab.value }]"
        @click="changeTab(tab.value)"
      >
        {{ tab.name }}
      </div>
    </div>

    <!-- 空订单状态 -->
    <div class="empty-orders" v-if="filteredOrders.length === 0">
      <div class="empty-icon">
        <i class="fas fa-file-alt"></i>
      </div>
      <div class="empty-text">您还没有任何订单</div>
      <router-link to="/home" class="btn btn-primary">去逛逛</router-link>
    </div>

    <!-- 订单列表 -->
    <div class="orders-container" v-else>
      <div class="order-card" v-for="order in filteredOrders" :key="order.orderId">
        <div class="order-header">
          <div class="store-info">
            <i class="fas fa-store store-icon"></i>
            <div class="store-name">{{ order.storeName }}</div>
          </div>
          <div class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</div>
        </div>
        
        <div class="order-content">  
          <!-- 显示orderItems数据（优先） -->
          <template v-if="order.orderItems && order.orderItems.length > 0">
            <div class="product-row" v-for="(item, index) in order.orderItems" :key="item.orderItemId + '-' + index" @click="goToProductDetail(item.productId)">
              <div class="product-image no-image" v-if="!item.productImage">
                <i class="iconfont icon-photo"></i>
              </div>
              <img v-else class="product-image" :src="item.productImage" :alt="item.productName">
              <div class="product-info">
                <div class="product-name">{{ item.productName || '订单商品' }}</div>
                <div class="product-price-row">
                  <div class="product-price">¥{{ item.price }}</div>
                  <div class="product-count">x{{ item.quantity || 1 }}</div>
                </div>
                <div class="product-spec-row">
                  <div class="product-spec">{{ getProductSpec(item, order) }}</div>
                  <!-- 评价按钮根据评价状态显示 -->
                  <button
                    v-if="order.status === 'completed'"
                    class="review-button"
                    :class="{ 'reviewed': isProductReviewed(order, item.productId) }"
                    :disabled="isProductReviewed(order, item.productId)"
                    @click.stop="reviewProduct(order.orderId, item.productId, item.orderItemId)">
                    {{ isProductReviewed(order, item.productId) ? '已评价' : '评价' }}
                  </button>
                </div>
              </div>
            </div>
          </template>

          <!-- 如果没有orderItems，显示productsItems -->
          <template v-else-if="order.productsItems && order.productsItems.length > 0">
            <div class="product-row" v-for="(item, index) in order.productsItems" :key="item.productId + '-' + index" @click="goToProductDetail(item.productId || item.id)">
              <img class="product-image" :src="getProductImage(item)" :alt="item.name">
              <div class="product-info">
                <div class="product-name">{{ item.name || '未知商品' }}</div>
                <div class="product-price-row">
                  <div class="product-price">¥{{ item.price }}</div>
                  <div class="product-count">x{{ getItemQuantity(order.orderItems, item.productId) }}</div>
                </div>
                <div class="product-spec-row">
                  <div class="product-spec">{{ getProductSpec(item, order) }}</div>
                  <!-- 评价按钮根据评价状态显示 -->
                  <button
                    v-if="order.status === 'completed'"
                    class="review-button"
                    :class="{ 'reviewed': isProductReviewed(order, item.productId) }"
                    :disabled="isProductReviewed(order, item.productId)"
                    @click.stop="reviewProduct(order.orderId, item.productId, getOrderItemId(order.orderItems, item.productId))">
                    {{ isProductReviewed(order, item.productId) ? '已评价' : '评价' }}
                  </button>
                </div>
              </div>
            </div>
          </template>
          
          <!-- 完全没有商品信息时显示 -->
          <div class="product-row" v-else>
            <div class="product-image no-image">
              <i class="iconfont icon-photo"></i>
            </div>
            <div class="product-info">
              <div class="product-name">订单商品</div>
              <div class="product-attr">订单号: {{ order.orderNumber }}</div>
            </div>
          </div>
        </div>
        
        <div class="order-footer">
          <div class="order-info-row">
            <div class="order-time">{{ formatOrderTime(order.createTime) }}</div>
            <div class="order-total">
              共{{ getTotalQuantity(order) }}件商品，实付：<span class="total-price">¥{{ order.totalAmount }}</span>
            </div>
          </div>
          <div class="order-actions">
            <!-- 待收货状态 -->
            <template v-if="order.status === 'pending_receipt'">
              <button class="order-button order-button-outline" @click="viewLogistics(order.orderId)">查看物流</button>
              <button class="order-button order-button-primary" @click="confirmReceipt(order.orderId)">确认收货</button>
            </template>
            <!-- 待付款状态 -->
            <template v-else-if="order.status === 'pending_payment'">
              <button class="order-button order-button-outline" @click="cancelOrder(order.orderId)">取消订单</button>
              <button class="order-button order-button-danger" @click="payOrder(order.orderId)">立即付款</button>
            </template>
            <!-- 已完成状态 -->
            <template v-else-if="order.status === 'completed'">
              <button class="order-button order-button-outline" @click="buyAgain(order.orderId)">再次购买</button>
              <button class="order-button order-button-outline" @click="deleteOrder(order.orderId)">删除订单</button>
            </template>
            <!-- 已取消状态 -->
            <template v-else-if="order.status === 'cancelled'">
              <button class="order-button order-button-outline" @click="buyAgain(order.orderId)">再次购买</button>
              <button class="order-button order-button-outline" @click="deleteOrder(order.orderId)">删除订单</button>
            </template>
            <!-- 待发货状态 -->
            <template v-else-if="order.status === 'pending_shipping'">
              <button class="order-button order-button-outline" @click="contactSeller(order.orderId)">联系卖家</button>
              <button class="order-button order-button-outline" @click="cancelOrder(order.orderId)">取消订单</button>
            </template>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部导航 -->
    <TabBar activeTab="profile" />
  </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import TabBar from '@/components/TabBar.vue';
import api from '@/network/api';
import { showToast, showDialog } from 'vant';
import axios from 'axios';

export default defineComponent({
  name: 'OrdersView',
  components: {
    TabBar
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const orders = ref([]);
    const loading = ref(true);
    const currentTab = ref('all');
    
    // 标签选项
    const tabs = [
      { name: '全部', value: 'all' },
      { name: '待付款', value: 'pending_payment' },
      { name: '待发货', value: 'pending_shipping' }, // 修改为后端实际使用的状态值
      { name: '待收货', value: 'pending_receipt' },
      { name: '已完成', value: 'completed' },
      { name: '已取消', value: 'cancelled' }
    ];

    // 根据状态获取显示文本
    const getStatusText = (status) => {
      const statusMap = {
        'pending_payment': '待付款',
        'pending_shipping': '待发货',
        'pending_receipt': '待收货',
        'completed': '已完成',
        'cancelled': '已取消'
      };
      return statusMap[status] || '未知状态';
    };

    // 根据状态获取CSS类
    const getStatusClass = (status) => {
      const classMap = {
        'pending_payment': 'status-payment',
        'pending_shipping': 'status-shipping',
        'pending_receipt': 'status-receipt',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled'
      };
      return classMap[status] || '';
    };

    // 切换标签
    const changeTab = (tab) => {
      currentTab.value = tab;
      // 更新路由参数，便于分享和刷新页面时保持状态
      if (tab !== 'all') {
        router.replace({ query: { ...route.query, status: tab } });
      } else {
        const { status, ...otherQueries } = route.query;
        router.replace({ query: otherQueries });
      }
      // 重新获取订单数据
      fetchOrders();
    };

    // 过滤订单
    const filteredOrders = computed(() => {
      if (currentTab.value === 'all') {
        return orders.value;
      } else {
        return orders.value.filter(order => order.status === currentTab.value);
      }
    });

    // 存储已评价的商品信息
    const reviewedProducts = ref([]);

    // 检查商品是否已评价
    const isProductReviewed = (order, productId) => {
      // 检查orderItems数组
      if (order && order.orderItems && Array.isArray(order.orderItems)) {
        // 查找对应商品ID的订单项
        const orderItem = order.orderItems.find(item => item.productId === productId);
        // 如果找到订单项且isReviewed为1，表示已评价
        if (orderItem && orderItem.isReviewed === 1) {
          return true;
        }
      }

      // 如果没有找到或者isReviewed不为1，则未评价
      return false;
    };

    // 静态演示数据
    const mockOrders = [
      {
        orderId: 1,
        storeName: '宠物乐园',
        status: 'pending_receipt',
        items: [
          {
            productId: 101,
            name: '宠物高级狗粮 全营养配方 10kg装',
            attributes: '牛肉味',
            price: 129,
            quantity: 1,
            specValue: '净含量：10kg/包 口味：牛肉味',
            image: 'https://images.unsplash.com/photo-1589924691995-400dc9ecc119?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60'
          }
        ],
        totalAmount: '245.00',
        createTime: '2023-05-20 14:30:00'
      },
      {
        orderId: 2,
        storeName: '萌宠之家',
        status: 'pending_payment',
        items: [
          {
            productId: 201,
            name: '多层猫爬架 带猫窝和磨爪柱 米白色',
            attributes: '四层',
            specValue: '颜色：米白色 规格：四层猫爬架',
            price: 258,
            quantity: 1,
            image: 'https://images.unsplash.com/photo-1545276880-75e4c3c6634e?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60'
          }
        ],
        totalAmount: '258.00',
        createTime: '2023-05-21 09:15:00'
      },
      {
        orderId: 3,
        storeName: '爱宠天地',
        status: 'completed',
        items: [
          {
            productId: 301,
            name: '舒适保暖宠物窝 可拆洗 适合中小型犬',
            attributes: '灰色',
            specValue: '尺寸：中号 颜色：灰色',
            price: 199,
            quantity: 1,
            image: 'https://images.unsplash.com/photo-1551717743-49959800b1f6?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60'
          }
        ],
        totalAmount: '199.00',
        createTime: '2023-05-15 16:45:00'
      }
    ];

    // 获取订单数据
    const fetchOrders = async () => {
      loading.value = true;
      try {
        // 传递当前标签状态，后端接口要求必须传递status参数
        const status = currentTab.value === 'all' ? '' : currentTab.value;
        // 使用api.getOrders，而不是之前的api方式
        let response;
        try {
          // 尝试使用新的API接口获取订单列表
          response = await api.getOrders(status);
        } catch (apiError) {  
        }
        
        // 检查响应数据结构
        const responseData = response?.data?.data || response?.data || [];
        
        if (responseData && Array.isArray(responseData)) {

          // 转换后端数据格式为前端所需格式
          orders.value = responseData.map(order => {
            // 诊断日志 - 记录原始订单数据
    

            // 确保订单中包含所需的商品数据
            const processedOrder = {
              orderId: order.orderId,
              orderNumber: order.orderNumber,
              storeName: order.storeName || '未知店铺',
              status: order.status,
              productsItems: [],
              orderItems: Array.isArray(order.orderItems) ? order.orderItems : [],
              totalAmount: order.totalAmount?.toFixed(2) || '0.00',
              createTime: order.createdAt || order.createAt,
              // 接收后端传来的payment_method字段，用于决定默认支付方式
              paymentMethod: order.payment_method || order.paymentMethod || '',
              // 保存评价信息
              productReviews: order.productReviews || []
            };

            // 处理productsItems，确保包含规格信息
            if (order.items) {
              processedOrder.productsItems = [{
                ...order.items,
                name: order.items.productName || order.items.name,
                specValue: order.items.specValue || order.items.spec_value || 
                          (order.orderItems && order.orderItems[0] ? order.orderItems[0].specValue || order.orderItems[0].spec_value : null)
              }];
            } else if (order.productsItems && Array.isArray(order.productsItems)) {
              processedOrder.productsItems = order.productsItems.map(item => {
                // 尝试从orderItems中找匹配的商品项，获取规格信息
                let specValue = item.specValue || item.spec_value;
                
                // 如果没有规格信息，尝试从orderItems中获取
                if (!specValue && order.orderItems && Array.isArray(order.orderItems)) {
                  const matchingOrderItem = order.orderItems.find(orderItem => 
                    orderItem.productId === item.productId || orderItem.productId === item.id);
                  
                  if (matchingOrderItem) {
                    specValue = matchingOrderItem.specValue || matchingOrderItem.spec_value || 
                               matchingOrderItem.productVariant;
                  }
                }
                
                return {
                  ...item,
                  specValue: specValue
                };
              });
            }


            // 处理orderItems，确保包含规格信息和订单项长度>0
            if (order.orderItems) {
              // 确保orderItems是数组
              if (!Array.isArray(order.orderItems)) {
                // 如果不是数组，尝试转换成数组
                try {
                  if (typeof order.orderItems === 'object') {
                    processedOrder.orderItems = Object.values(order.orderItems);
                  } else {
                    processedOrder.orderItems = [];
                  }
                } catch (e) {
                  processedOrder.orderItems = [];
                }
              } else {
                processedOrder.orderItems = order.orderItems.map(item => {
                  // 获取规格信息，优先使用specValue，然后是spec_value，最后是productVariant
                  let specValue = item.specValue || item.spec_value || item.productVariant;
                  
                  return {
                    ...item,
                    specValue: specValue
                  };
                });
              }           
            }

            // 如果处理后仍然没有规格信息，尝试从原始数据中查找
            if (processedOrder.orderItems && processedOrder.orderItems.length > 0) {
              const sampleItem = processedOrder.orderItems[0];
              if (!sampleItem.specValue && order.spec_value) {
                // 将订单级别的规格信息应用到所有商品项
                processedOrder.orderItems = processedOrder.orderItems.map(item => ({
                  ...item,
                  specValue: order.spec_value
                }));
              }
            }

            // 如果存在评价信息，添加到reviewedProducts中
            if (order.productReviews && Array.isArray(order.productReviews)) {
              order.productReviews.forEach(review => {
                reviewedProducts.value.push({
                  orderId: order.orderId,
                  productId: review.productId
                });
              });
            }


            return processedOrder;
          });
        } else {
          // 如果API返回格式不正确，使用模拟数据
          orders.value = [...mockOrders];
        }
      } catch (error) {
        showToast('获取订单列表失败，已显示本地数据');
        
        // 使用静态数据作为备用
        orders.value = [...mockOrders];
        
        // 如果当前选中了特定标签，过滤静态数据
        if (currentTab.value !== 'all') {
          orders.value = orders.value.filter(order => order.status === currentTab.value);
        }
      } finally {
        loading.value = false;
      }
    };

    // 获取用户已评价的商品列表
    const fetchReviewedProducts = async () => {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        const userId = userInfo.data?.userId || userInfo.userId;

        if (!userId) return;

        // 调用API获取用户已评价商品列表
        const response = await api.getProductReviews(0, { userId });

        if (response && response.code === 100 && Array.isArray(response.data)) {
          // 更新reviewedProducts
          response.data.forEach(review => {
            reviewedProducts.value.push({
              orderId: review.orderId,
              productId: review.productId
            });
          });
        }
      } catch (error) {
        console.error('获取已评价商品失败:', error);
      }
    };

    // 查看物流
    const viewLogistics = (orderId) => {
      // 跳转到物流信息页面
      router.push({
        name: 'orderLogistics',
        params: { id: orderId }
      });
    };

    // 通用对话框操作函数
    const showActionDialog = (title, message, confirmText, cancelText, onConfirm) => {
      showDialog({
        title,
        message,
        showCancelButton: true,
        confirmButtonText: confirmText,
        cancelButtonText: cancelText
      }).then(action => {
        if (action === 'confirm') {
          onConfirm();
        }
      }).catch(err => {
        // 用户取消或发生错误时不做任何操作，防止未处理的Promise错误
      });
    };
    
    // 确认收货
    const confirmReceipt = async (orderId) => {
      try {
        showActionDialog(
          '确认收货', 
          '确认已收到商品吗？确认后无法撤销', 
          '确认收货', 
          '取消',
          async () => {
            try {
              const response = await api.confirmReceipt(orderId);
              
              // 根据后端状态码定义，SUCCESS = 100
              if (response && response.code === 100) {
                showToast('确认收货成功');
                fetchOrders(); // 刷新订单列表
              } else {
                // 处理其他状态码
                const errorMsg = response?.message || response?.msg || '确认收货失败';
                showToast(errorMsg);
              }
            } catch (innerError) {
              showToast('网络请求失败，请检查网络连接');
            }
          }
        );
      } catch (error) {
        showToast('确认收货失败，请稍后再试');
      }
    };

    // 取消订单
    const cancelOrder = async (orderId) => {
      try {
        showActionDialog(
          '取消订单',
          '确定要取消此订单吗？',
          '确认取消',
          '不取消',
          async () => {
            try {
              const response = await api.cancelOrder(orderId);
              
              // 根据后端状态码定义，SUCCESS = 100
              if (response && response.code === 100) {
                showToast('订单已取消');
                fetchOrders(); // 刷新订单列表
              } else {
                // 处理其他状态码
                const errorMsg = response?.message || response?.msg || '订单取消失败';
                showToast(errorMsg);
              }
            } catch (innerError) {
              showToast('网络请求失败，请检查网络连接');
            }
          }
        );
      } catch (error) {
        showToast('取消订单失败，请稍后再试');
      }
    };

    // 删除订单
    const deleteOrder = async (orderId) => {
      try {
        showActionDialog(
          '删除订单',
          '确定要删除此订单吗？删除后将无法恢复',
          '确认删除',
          '取消',
          async () => {
            try {
              const response = await api.deleteOrder(orderId);
              
              // 根据后端状态码定义，SUCCESS = 100
              if (response && response.code === 100) {
                showToast('订单已删除');
                fetchOrders(); // 刷新订单列表
              } else {
                // 处理其他状态码
                const errorMsg = response?.message || response?.msg || '订单删除失败';
                showToast(errorMsg);
              }
            } catch (innerError) {
              // 如果后端API不支持，模拟删除操作
              orders.value = orders.value.filter(order => order.orderId !== orderId);
              showToast('订单已删除');
            }
          }
        );
      } catch (error) {
        showToast('删除订单失败，请稍后再试');
      }
    };

    // 支付订单
    const payOrder = (orderId) => {
      // 查找对应的订单信息
      const order = orders.value.find(o => o.orderId === orderId);
      
      // 构建URL参数
      let paymentUrl = `/payment?orderId=${orderId}`;
      
      // 如果订单数据中包含支付方式，则加入URL参数
      if (order && order.paymentMethod) {
        paymentUrl += `&paymentMethod=${order.paymentMethod}`;
      }
      
      // 跳转到支付页面
      router.push(paymentUrl);
    };

    // 再次购买
    const buyAgain = async (orderId) => {
      try {
        // 查找对应的订单
        const order = orders.value.find(o => o.orderId === orderId);
        
        if (!order) {
          showToast('找不到订单信息');
          return;
        }

        // 准备商品列表
        let productsList = [];
        
        // 从orderItems获取商品信息
        if (order.orderItems && Array.isArray(order.orderItems) && order.orderItems.length > 0) {
          productsList = order.orderItems.map(item => {
            return {
              productId: item.productId,
              quantity: item.quantity || 1,
              storeId: item.storeId || order.storeId,
              specValue: item.specValue || item.spec_value,
              name: item.productName || item.name,
              price: item.price,
              mainImage: "" // 将图片设置为空字符串
            };
          });
        }
        // 如果没有orderItems，尝试从productsItems获取
        else if (order.productsItems && Array.isArray(order.productsItems) && order.productsItems.length > 0) {
          productsList = order.productsItems.map(item => {
            return {
              productId: item.productId || item.id,
              quantity: item.quantity || 1,
              storeId: item.storeId || order.storeId,
              specValue: item.specValue || item.spec_value,
              name: item.name,
              price: item.price,
              mainImage: "" // 将图片设置为空字符串
            };
          });
        }

        if (productsList.length === 0) {
          showToast('订单中没有商品信息');
          return;
        }

        showToast('正在处理，请稍候...');
        
        // 调用再次购买API
        const response = await api.repeatPurchase(productsList);
        
        if (response && response.code === 100) {
          showToast('已成功加入购物车');
          // 可以选择跳转到购物车页面
          router.push('/cart');
        } else {
          showToast(response?.message || '再次购买失败');
        }
      } catch (error) {
        showToast('操作失败，请稍后再试');
      }
    };

    // 添加获取orderItemId的辅助函数
    const getOrderItemId = (orderItems, productId) => {
      if (!orderItems) return 0;
      const item = orderItems.find(item => item.productId === productId);
      return item ? item.orderItemId : 0;
    };

    // 评价商品 (修改为评价单个商品)
    const reviewProduct = async (orderId, productId, orderItemId) => {
      try {
        // 查找对应的订单
        const order = orders.value.find(o => o.orderId === orderId);
        
        // 检查商品是否已评价
        if (isProductReviewed(order, productId)) {
          showToast('该商品已评价');
          return;
        }

        // 跳转到评价页面，并传递订单ID和商品ID
        router.push({
          name: 'orderReview',
          query: {
            orderId: orderId,
            productId: productId,
            orderItemId: orderItemId
          }
        });
      } catch (error) {
        showToast('系统错误，请稍后再试');
      }
    };

    // 联系卖家
    const contactSeller = (orderId) => {
      // 这里应该获取卖家联系方式并跳转到聊天页面
      // 由于可能没有聊天功能，这里简单提示
      showToast('功能开发中，敬请期待');
    };

    // 添加获取商品数量的辅助函数
    const getItemQuantity = (orderItems, productId) => {
      if (!orderItems) return 1;
      const item = orderItems.find(item => item.productId === productId);
      return item ? item.quantity : 1;
    };

    // 添加商品图片获取辅助函数
    const getProductImage = (product) => {
      if (!product) return '';
      // 检查多种可能的图片字段
      const imageUrl = product.image || product.mainImage || product.productImage;
      if (imageUrl) {
        // 如果图片URL不是完整的URL，则需要拼接服务器地址
        if (imageUrl.startsWith('http')) {
          return imageUrl;
        } else {
          // 假设后端资源URL前缀
          return `${process.env.VUE_APP_API_URL || ''}${imageUrl}`;
        }
      }
      return 'https://via.placeholder.com/60x60?text=No+Image';
    };

    // 格式化订单时间
    const formatOrderTime = (time) => {
      if (!time) return '';
      const date = new Date(time);
      if (isNaN(date.getTime())) return time; // 如果转换失败，直接返回原始值
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    };

    // 获取订单总数量
    const getTotalQuantity = (order) => {
      let total = 0;
      
      if (order.orderItems && Array.isArray(order.orderItems)) {
        total = order.orderItems.reduce((sum, item) => sum + (item.quantity || 1), 0);
      } else if (order.productsItems && Array.isArray(order.productsItems)) {
        order.productsItems.forEach(item => {
          total += getItemQuantity(order.orderItems, item.productId);
        });
      }
      
      return total || 1; // 默认至少返回1
    };

    // 在script部分添加折叠状态管理
    const expandedOrders = ref([]);

    // 切换订单展开状态
    const toggleOrderExpand = (orderId) => {
      if (expandedOrders.value.includes(orderId)) {
        expandedOrders.value = expandedOrders.value.filter(id => id !== orderId);
      } else {
        expandedOrders.value.push(orderId);
      }
    };

    // 修改isDebug计算属性，确保可以看到调试信息
    const isDebug = computed(() => {
      // 强制显示调试信息
      return true;
    });

    // 添加getProductSpec辅助函数
    const getProductSpec = (item, order) => {
      // 首先检查当前item中是否有规格信息
      if (item.specValue) return item.specValue;
      if (item.spec_value) return item.spec_value;
      if (item.productVariant) return item.productVariant;
      if (item.description) return item.description;
      if (item.attributes) return item.attributes;
      
      // 检查是否有productId，如果有则尝试从orderItems中查找匹配项
      if (item.productId && order.orderItems && Array.isArray(order.orderItems)) {
        const matchingOrderItem = order.orderItems.find(orderItem => 
          orderItem.productId === item.productId);
        if (matchingOrderItem) {
          if (matchingOrderItem.specValue) return matchingOrderItem.specValue;
          if (matchingOrderItem.spec_value) return matchingOrderItem.spec_value;
          if (matchingOrderItem.productVariant) return matchingOrderItem.productVariant;
        }
      }
      
      // 检查items中是否有规格信息
      if (order.items) {
        if (order.items.specValue) return order.items.specValue;
        if (order.items.spec_value) return order.items.spec_value;
      }
      
      // 最后从productsItems中查找
      if (item.productId && order.productsItems && Array.isArray(order.productsItems)) {
        const matchingProductItem = order.productsItems.find(productItem => 
          productItem.productId === item.productId || productItem.id === item.productId);
        if (matchingProductItem) {
          if (matchingProductItem.specValue) return matchingProductItem.specValue;
          if (matchingProductItem.spec_value) return matchingProductItem.spec_value;
          if (matchingProductItem.description) return matchingProductItem.description;
          if (matchingProductItem.attributes) return matchingProductItem.attributes;
        }
      }
      
      // 如果都找不到，返回默认值
      return '默认规格';
    };

    // 跳转到商品详情页
    const goToProductDetail = (productId) => {
      if (!productId) {
        showToast('商品信息不完整');
        return;
      }
      router.push(`/product/${productId}`);
    };

    onMounted(() => {
      // 从路由参数中获取状态
      if (route.query.status) {
        // 设置当前选中的标签
        const status = String(route.query.status);
        
        // 特殊处理：如果URL中传入的是pending_shipment，确保高亮显示待发货选项卡
        if (status === 'pending_shipment') {
          // 将旧的状态值转换为新的状态值
          currentTab.value = 'pending_shipping';
        } else {
          currentTab.value = status;
        }
      }
      
      fetchOrders();
    });

    return {
      orders,
      loading,
      currentTab,
      tabs,
      filteredOrders,
      getStatusText,
      getStatusClass,
      changeTab,
      viewLogistics,
      confirmReceipt,
      cancelOrder,
      payOrder,
      buyAgain,
      reviewProduct,
      contactSeller,
      getItemQuantity,
      getProductImage,
      getOrderItemId,
      isProductReviewed,
      formatOrderTime,
      getTotalQuantity,
      expandedOrders,
      toggleOrderExpand,
      isDebug,
      getProductSpec,
      deleteOrder,
      goToProductDetail
    };
  }
});
</script>

<style scoped>
.order-list-container {
  padding-bottom: 55px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.navbar {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.navbar-back {
  margin-right: 15px;
  color: #333;
  font-size: 18px;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-weight: 500;
  font-size: 16px;
  color: #333;
}

.tab-bar {
  display: flex;
  background-color: white;
  padding: 0;
  margin-bottom: 10px;
  position: sticky;
  top: 51px; /* navbar的高度 */
  z-index: 5;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 14px;
  color: #666;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-item.active {
  color: #3490dc; /* 橙色文字 */
  font-weight: 500;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 3px;
  background-color: #3490dc; /* 橙色下划线光标 */
  border-radius: 3px;
}

.orders-container {
  padding: 12px;
}

.order-card {
  background-color: white;
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 14px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.store-info {
  display: flex;
  align-items: center;
}

.store-icon {
  margin-right: 8px;
  color: #666;
  font-size: 15px;
}

.store-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.order-status {
  font-size: 14px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 10px;
}

.status-payment {
  color: #f59e0b;
  background-color: #fef3c7;
}

.status-shipping {
  color: #3b82f6;
  background-color: #dbeafe;
}

.status-receipt {
  color: #10b981;
  background-color: #d1fae5;
}

.status-completed {
  color: #6b7280;
  background-color: #f3f4f6;
}

.status-cancelled {
  color: #ff6e26;
  background-color: #fef3c7;
}

.order-content {
  padding: 16px;
}

.product-row {
  display: flex;
  margin-bottom: 16px;
  position: relative;
  align-items: flex-start;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 12px;
  border: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.no-image {
  background-color: #f7f7f7;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: calc(100% - 92px); /* 考虑到图片的宽度和margin */
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  font-weight: 500;
}

.product-spec-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.product-spec {
  font-size: 12px;
  color: #666;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 3px 8px;
  display: inline-block;
  border: 1px solid #e2e8f0;
  margin-right: 10px;
  flex: 1;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 6px;
}

.product-price {
  font-size: 15px;
  color: #ff6e26;
  font-weight: 600;
}

.product-count {
  font-size: 13px;
  color: #999;
}

.order-footer {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.order-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-total {
  font-size: 14px;
  color: #666;
}

.total-price {
  color: #ff6e26;
  font-weight: 600;
  font-size: 16px;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
}

.order-button {
  margin-left: 10px;
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 13px;
  border: 1px solid #dcdfe6;
  background-color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.order-button-outline {
  color: #666;
  border: 1px solid #dcdfe6;
}

.order-button-outline:hover {
  color: #333;
  border-color: #ccc;
}

.order-button-primary {
  color: #3490dc;
  border: 1px solid #3490dc;
}

.order-button-primary:hover {
  background-color: #fff0eb;
}

.order-button-danger {
  color: white;
  background-color: #3490dc;
  border: 1px solid #3490dc;
}

.order-button-danger:hover {
  background-color: #3994de;
}

.review-button {
  padding: 4px 12px;
  border-radius: 14px;
  font-size: 12px;
  color: #3490dc;
  border: 1px solid #3490dc;
  background-color: white;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.review-button:hover {
  background-color: #fff0eb;
}

.review-button.reviewed {
  color: #999;
  border-color: #ccc;
  background-color: #f5f5f5;
  cursor: default;
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  background-color: white;
  border-radius: 12px;
  margin: 20px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.empty-icon {
  font-size: 50px;
  color: #ccc;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 15px;
  color: #666;
  margin-bottom: 25px;
}

.btn {
  padding: 10px 24px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background-color: #3490dc;
  color: white;
  border: none;
}

.btn-primary:hover {
  background-color: #3e93d9;
}

.collapsible-content {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #ebeef5;
}

.collapse-toggle {
  text-align: center;
  padding: 10px 0;
  margin: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #666;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px dashed #ddd;
  display: block !important; /* 强制显示 */
  position: relative;
  z-index: 1;
}

.collapse-toggle::before {
  content: '';
  position: absolute;
  left: 50%;
  top: -3px;
  transform: translateX(-50%);
  width: 30px;
  height: 6px;
  background-color: white;
  z-index: -1;
}

.collapse-toggle:hover {
  background-color: #f0f0f0;
  color: #3490dc;
  border-color: #3490dc;
}

.collapse-toggle i {
  margin-right: 5px;
}

.debug-info {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}
</style>